package cn.tedu.rms.tables.service.impl;

import cn.tedu.rms.base.enums.ReservationTimes;
import cn.tedu.rms.base.enums.TablesStatus;
import cn.tedu.rms.branch.mapper.BranchMapper;
import cn.tedu.rms.branch.pojo.vo.BranchVO;
import cn.tedu.rms.orders.mapper.OrdersMapper;
import cn.tedu.rms.orders.pojo.dto.OrdersQuery;
import cn.tedu.rms.orders.pojo.entity.Orders;
import cn.tedu.rms.orders.pojo.vo.OrdersVO;
import cn.tedu.rms.tables.mapper.TablesMapper;
import cn.tedu.rms.tables.pojo.dto.TablesQuery;
import cn.tedu.rms.tables.pojo.dto.TablesSaveParam;
import cn.tedu.rms.tables.pojo.entity.Tables;
import cn.tedu.rms.tables.pojo.vo.TablesVO;
import cn.tedu.rms.tables.service.TablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class TablesServiceImpl implements TablesService {
    @Autowired
    private TablesMapper tablesMapper;
    @Autowired
    private BranchMapper branchMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Override
    public void saveTables(TablesSaveParam tablesSaveParam) {
        log.debug("保存餐桌信息业务，参数：{}",tablesSaveParam);
        Tables tables = new Tables();
        BeanUtils.copyProperties(tablesSaveParam,tables);
        if(tablesSaveParam.getId()==null){
            //新增
            tables.setStatus(TablesStatus.STATUS_ENABLED.getCode());
            tables.setRepastStatus(TablesStatus.REPAST_FREE.getCode());
            tables.setTimeOne(TablesStatus.TIME_NUM_NO.getCode());
            tables.setTimeTwo(TablesStatus.TIME_NUM_NO.getCode());
            tables.setTimeThree(TablesStatus.TIME_NUM_NO.getCode());
            tables.setTimeFour(TablesStatus.TIME_NUM_NO.getCode());
            tables.setTimeFive(TablesStatus.TIME_NUM_NO.getCode());
            tables.setCreateTime(new Date());
            tablesMapper.insert(tables);
        }else{
            //修改
            tables.setUpdateTime(new Date());
            // 如果就餐状态为就餐中，才判断餐桌状态否为为预约
            if(tables.getRepastStatus().equals(TablesStatus.REPAST_FREE.getCode())){
                // 查询该餐桌五个时间段中是否还有预约状态
                TablesVO tablesVO = tablesMapper.selectById(tables.getId());
                if(TablesStatus.TIME_NUM_YES.getCode().equals(tablesVO.getTimeOne())
                        ||TablesStatus.TIME_NUM_YES.getCode().equals(tablesVO.getTimeTwo())
                        ||TablesStatus.TIME_NUM_YES.getCode().equals(tablesVO.getTimeThree())
                        ||TablesStatus.TIME_NUM_YES.getCode().equals(tablesVO.getTimeFour())
                        ||TablesStatus.TIME_NUM_YES.getCode().equals(tablesVO.getTimeFive())
                ){
                    tables.setRepastStatus(TablesStatus.REPAST_RESERVED.getCode());
                }
            }
            // 更新餐桌的状态
            tablesMapper.update(tables);
            // 通过餐桌id和餐桌状态查询该餐桌是否被使用
            OrdersQuery ordersQuery = new OrdersQuery();
            ordersQuery.setTableId(tables.getId());
            ordersQuery.setDiningStatus("1");
            List<OrdersVO> list = ordersMapper.selectOrders(ordersQuery);
            if(list.size()>0){
                // 有数据的话需要更新该订单的状态
                Orders orders = new Orders();
                orders.setId(list.get(0).getId());
                // 就餐结束状态
                orders.setDiningStatus("2");
                ordersMapper.updateOrder(orders);
            }
        }
    }

    @Override
    public void deleteTablesById(Long id) {
        log.debug("根据餐桌id删除餐桌，参数：{}",id);
        tablesMapper.deleteById(id);

    }

    @Override
    public List<TablesVO> selectTables(TablesQuery tablesQuery) {
        log.debug("查询餐桌信息业务，参数：{}",tablesQuery);
        List<TablesVO> tablesVOList = tablesMapper.select(tablesQuery);
        for(TablesVO table : tablesVOList){
            BranchVO branchVO = branchMapper.selectById(table.getBranchId());
            table.setBranchName(branchVO.getName());
        }
        log.debug("查询餐桌信息业务，参数：{},餐桌信息结果List:{}",tablesQuery,tablesVOList);
        return tablesVOList;
    }

    @Override
    public List<TablesVO> selectTablesCustomer(TablesQuery tablesQuery) {
        log.debug("顾客查询餐桌信息业务，参数：{}",tablesQuery);
        /*String timePeriod = timeNowBelong(new Date());
        setPropertyOfTimePeriod(timePeriod,tablesQuery);
        log.debug("顾客查询餐桌信息业务，参数：{}",tablesQuery);*/
        List<TablesVO> tablesVOList = tablesMapper.selectForCustomer(tablesQuery);
        log.debug("顾客查询餐桌信息业务，参数：{},餐桌信息结果List:{}",tablesQuery,tablesVOList);

        filterTablesList(tablesVOList);

        log.debug("顾客查询餐桌信息业务，参数：{},过滤后的餐桌信息结果List:{}",tablesQuery,tablesVOList);
        log.warn("1,{}",tablesVOList);
        for(TablesVO table : tablesVOList){
            BranchVO branchVO = branchMapper.selectById(table.getBranchId());
            table.setBranchName(branchVO.getName());
        }
        log.debug("顾客查询餐桌信息业务，参数：{},餐桌信息最终结果List:{}",tablesQuery,tablesVOList);
        return tablesVOList;
    }

    /**
     * 判断当前时间~当前时间+1小时，属于哪个时间段/哪两个时间段
     */
    public String timeNowBelong(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        String timeStart = simpleDateFormat.format(date);//当前时间String eg: 17:55:59

        //把当前时间转化为时间戳
        long time = date.getTime();
        //定义一天的时间戳86400000
        long day=86400000;
        //一小时的时间戳
        long hour = day/24;
        Date dateAppendTwoHour = new Date(time+2*hour);
        String timeEnd = simpleDateFormat.format(dateAppendTwoHour);//当前时间+2小时String eg: 19:55:59

        System.out.println(timeStart);
        System.out.println(timeEnd);
        String[] strTimes = new String[]{"00:00:00","08:00:00","12:00:00","16:00:00","20:00:00","23:59:59"};

        int number = -1;
        /*可能出现跨天的情况，那么一定不属于某一个时间段，属于第五和第一，time_five_one
        23:09:15
        01:09:15
        time_one*/
        if(timeStart.compareTo(timeEnd)>0){
            return "time_five_one";
        }
        for (int i = 0; i < 5; i++) {
            if(timeStart.compareTo(strTimes[i])>=0&&timeEnd.compareTo(strTimes[i+1])<0){
                number=i;
                break;
            }
        }
        if(number == -1){
            for (int i = 5; i < 9; i++) {
                if(timeStart.compareTo(strTimes[i-5])>=0&&timeEnd.compareTo(strTimes[i-5+2])<0){
                    number=i;
                    break;
                }
            }
        }

        switch(number){
            case 0:
                return ReservationTimes.TIME_ONE.getTimePeriod();
            case 1:
                return ReservationTimes.TIME_TWO.getTimePeriod();
            case 2:
                return ReservationTimes.TIME_THREE.getTimePeriod();
            case 3:
                return ReservationTimes.TIME_FOUR.getTimePeriod();
            case 4:
                return ReservationTimes.TIME_FIVE.getTimePeriod();
            case 5:
                return "time_one_two";
            case 6:
                return "time_two_three";
            case 7:
                return "time_three_four";
            case 8:
                return "time_four_five";
            default:
                return null;
        }
    }
    /**
     * 判断当前时间段所处的一个餐桌时间段或连续两个时间段是否可用
     */

    public boolean tableIsAvailable(String timePeriod,TablesVO tablesVO){
        System.out.println("tableIsA"+timePeriod);
        boolean result = false;
        switch (timePeriod){
            case "time_one":
                if("0".equals(tablesVO.getTimeOne())){
                    result = true;
                }
                break;
            case "time_two":
                if("0".equals(tablesVO.getTimeTwo())){
                    result = true;
                }
                break;
            case "time_three":
                if("0".equals(tablesVO.getTimeThree())){
                    result = true;
                }
                break;
            case "time_four":
                if("0".equals(tablesVO.getTimeFour())){
                    result = true;
                }
                break;
            case "time_five":
                if("0".equals(tablesVO.getTimeFive())){
                    result = true;
                }
                break;
            case "time_one_two":
                if("0".equals(tablesVO.getTimeOne())&&"0".equals(tablesVO.getTimeTwo())){
                    result = true;
                }
                break;
            case "time_two_three":
                if("0".equals(tablesVO.getTimeTwo())&&"0".equals(tablesVO.getTimeThree())){
                    result = true;
                }
                break;
            case "time_three_four":
                if("0".equals(tablesVO.getTimeThree())&&"0".equals(tablesVO.getTimeFour())){
                    result = true;
                }
                break;
            case "time_four_five":
                if("0".equals(tablesVO.getTimeFour())&&"0".equals(tablesVO.getTimeFive())){
                    result = true;
                }
                break;
            case "time_five_one":
                if("0".equals(tablesVO.getTimeFive())&&"0".equals(tablesVO.getTimeOne())){
                    result = true;
                }
                break;
        }
        System.out.println(result);
        return result;
    }
    /**
     * 给餐桌的5个时间段的状态值，存放到数组中
     */
    /*public String[] saveTimePeriodsToArray(TablesVO tablesVO){
        String[] strArr = new String[5];
        strArr[0] = tablesVO.getTimeOne();
        strArr[1] = tablesVO.getTimeTwo();
        strArr[2] = tablesVO.getTimeThree();
        strArr[3] = tablesVO.getTimeFour();
        strArr[4] = tablesVO.getTimeFive();
        return strArr;
    }*/

    /**
     * 针对顾客能使用的餐桌集合进行过滤
     */
    public void filterTablesList(List<TablesVO> tablesVOList) {
        String timePeriod = timeNowBelong(new Date());
        System.out.println(timePeriod);
        Iterator<TablesVO> iterator = tablesVOList.iterator();
        while (iterator.hasNext()) {
            TablesVO tablesVO = iterator.next();
            boolean isAvailable = tableIsAvailable(timePeriod, tablesVO);
            if (!isAvailable) {
                System.out.println("tablesVOList.remove(tablesVO)");
                iterator.remove();
            }
        }
    }

}
